package com.dhh.sky.util;

import java.io.*;
import android.os.Environment;
import android.util.Log;

public class EditorUtil {
	public final static int FILEFORMAT_NL = 1;
	public final static int FILEFORMAT_CR = 2;
	public final static int FILEFORMAT_CRNL = 3;
	
	public static String getFileContent(String fileName){
		StringBuffer sb = new StringBuffer();
		String path = Environment.getExternalStorageDirectory()+"/skydrive/"+fileName;
		File file = new File(path.toString());
		FileReader reader = null;
		try{
			reader = new FileReader(path.toString());
			if (file.length() != 0){			
				char[] buffer = new char[1024];
				int count = 0;
				do {
					count = reader.read(buffer, 0, 1000);
					if (count >= 0){
						sb.append(buffer, 0, count);
					}
				} while (count >= 0);
			}
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(), e);
		}finally{
			if(reader!=null){
				try {
					reader.close();
				} catch (IOException e) {
					Log.e(Constant.TAG, e.getMessage(), e);
				}
			}			
		}
		
		return sb.toString();
	}
	
	public static int getContentFormatType(String content){
		int format = FILEFORMAT_NL;
		
		if (content.indexOf("\r\n", 0) != -1){
			format = FILEFORMAT_CRNL;
		} else if(content.indexOf("\r", 0) != -1) {
			format = FILEFORMAT_CRNL;
		}
		
		return format;
	}
	
	public static String filerContentByFormat(String content,int format){
		String result = content;
		
		if (format == FILEFORMAT_CRNL){
			content = content.replace("\r", "");
		} else if(format == FILEFORMAT_CR) {
			content = content.replace("\r", "\n");
		}
		
		return result;
	}
	
	public static boolean saveFile(String fileName,String content,int formatType){
		boolean flag = false;
		
		String path = Environment.getExternalStorageDirectory()+"/skydrive/"+fileName;
		FileWriter fstream = null;
		BufferedWriter out = null;
		try{
			fstream = new FileWriter(path);
			out = new BufferedWriter(fstream);
			
			if (formatType == FILEFORMAT_CR){
				out.write(content.replace("\n", "\r"));
			} else if (formatType == FILEFORMAT_CRNL) {
				out.write(content.replace("\n", "\r\n"));
			} else {
				out.write(content);
			}
			out.flush();
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(), e);
		}finally{
			try{
				if(out!=null){
					out.close();
				}
				
				if(fstream!=null){
					fstream.close();
				}
			}catch(Exception e){
				Log.e(Constant.TAG, e.getMessage(), e);
			}
		}
		return flag;
	}
	
	
}
